package com.lz.security.handler;

import com.lz.pojo.SysUser;
import com.lz.security.pojo.LoginUser;
import com.lz.security.utils.JsonUtil;
import com.lz.security.utils.JwtUtil;
import com.lz.security.utils.SecurityUtil;
import com.lz.service.SysUserService;
import com.lz.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 登陆成功处理器
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserService sysUserService;

    /**
     *
     * @param request 请求
     * @param response 响应
     * @param authentication 当前登陆用户
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //请求成功响应json字符串
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        LoginUser loginuser = SecurityUtil.getLoginuser();
        //将jwt字符串放入到响应头
//        String jwtToken = JwtUtil.generateToken(loginuser,1000*60*60*24);
        String jwtToken = JwtUtil.generateTokenByMobile(loginuser.getMobile(),1000*60*60*24);
        response.setHeader("Authorization", "Bearer " + jwtToken);

        //token
        SysUser user = new  SysUser();
        user.setId(loginuser.getId());
        user.setToken("Bearer " +jwtToken);
        sysUserService.updateById(user);
        loginuser.setToken(user.getToken());
        response.getWriter().write(JsonUtil.toString(Result.success(loginuser)));

    }
}
